<template>
  <div class="publish-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 面包屑路径导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{
            $route.query.id ? "修改文章" : "发布文章"
          }}</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- /面包屑路径导航 -->
      </div>
      <el-form
        :rules="formRules"
        ref="publish-form"
        :model="article"
        label-width="60px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="article.title"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="ontent" >
          <el-tiptap
            lang="en"
            v-model="article.content"
            :extensions="extensions"
            output="html"
            placeholder="请输入你要写的内容"
            height="300px"
          />
          <!-- <el-input type="textarea" v-model="article.content"></el-input> -->
        </el-form-item>
        <el-form-item label="封面">
          <el-radio-group v-model="article.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <template  v-if="article.cover.type>0">
          <div class="uploadcover"> 
            <!-- 这个 $event就是子组件传递过来的参数  在默认情况下如果onUpadateCover在这个组件
            没有给参数 它就会显示子组件传递过来的参数
            这里给了个参数index  那么第二参数就是$event( 这才是子组件传递过来的参数)
             传递的时候只能通过这种形式进行参数的传递 ！！ 很饿好理解 事件传参    
             -->
             <!-- upload-coverimg 是一个子组件啊 -->

            <!-- <upload-coverimg
          :key="cover"
          v-for="(cover,index) in article.cover.type"
          @update-cover="onUpadateCover(index,$event)"  
           :cover-image="article.cover.images[index]"
           /> -->

           <!-- 使用v-model简写代码 
           当你给子组件提供的数据既要使用还要修改的时候我们可以使用v-model
           v-model="article.cover.images[index]" 其实干了两件事
           第一个给子组件传递了一个名字叫value的数据 :value="article.cover.images[index]"
            第二个默认监听 input事件 @input="article.cover.images[index]=事件参数"
           -->
            <upload-coverimg
          :key="cover"
          v-for="(cover,index) in article.cover.type"
           v-model="article.cover.images[index]"
           />
           
           </div>
           </template>
        </el-form-item>
        <el-form-item label="频道" prop="channel_id" >
          <el-select v-model="article.channel_id" placeholder="请选择频道">
            <el-option
              :label="channels.name"
              :value="channels.id"
              v-for="(channels, index) in channels"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit(false)">发表</el-button>
          <el-button @click="onSubmit(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
//引入图片组件
import UploadCoverimg from './components/upload-cover.vue'
import {
  getArticle,
  getArticleChannels,
  addArticle,
  updateArticle,
} from "@/api/article.js";
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Italic,
  Strike,
  Underline,
  Link,
  Image,
  Iframe,
  CodeBlock,
  Blockquote,
  ListItem,
  BulletList,
  OrderedList,
  TodoItem,
  TodoList,
  TextAlign,
  Indent,
  LineHeight,
  HorizontalRule,
  HardBreak,
  TrailingNode,
  History,
  Table,
  TableHeader,
  TableCell,
  TableRow,
  FormatClear,
  TextColor,
  TextHighlight,
  Preview,
  Print,
  Fullscreen,
  SelectAll,
  FontType,
  FontSize,
  // CodeView,
} from "element-tiptap";

import { uploadImage } from "@/api/image.js";
//样式
import "element-tiptap/lib/index.css";


export default {
  name: "PublishIndex",
  components: {
    "el-tiptap": ElementTiptap,
    UploadCoverimg
  },
   
  data() {
    return {
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      channels: [],
      article: {
        title: "", //标题
        content: "", //内容
        cover: {
          type: 0, //封面类型
          images: [], //地址
        },
        channel_id: null,
      },
      formRules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            min: 5,
            max: 30,
            message: "长度在 5 到 30 个字符",
            trigger: "blur",
          },
        ],
        content: [
          // { required: true, message: '请输入文章内容', trigger: 'change' }
          {
            validator(rule, value, callback) {
              console.log("content validator");
              if (value === "<p></p>") {
                // 验证失败
                callback(new Error("请输入文章内容"));
              } else {
                // 验证通过
                callback();
              }
            },
          },
          { required: true, message: "请输入文章内容", trigger: "blur" },
        ],
        channel_id: [{ required: true, message: "请选择文章频道" }],
      },
      //富文本编辑器
      extensions: [
        new Doc(),
        new Text(),
        new Image({
          uploadRequest(file) {
            // console.log(file);
            const fd = new FormData();
            fd.append("image", file);
            return uploadImage(fd).then((res) => {
              console.log(res);
              return res.data.data.url;
            });
          },
        }),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Underline({ bubble: true, menubar: false }), // 在气泡菜单而不在菜单栏中渲染菜单按钮
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new TodoItem(),
        new TodoList(),
        new TextAlign(),
        new Indent(),
        new LineHeight(),
        new HorizontalRule(),
        new HardBreak(),
        new TrailingNode(),
        new History(),
        new Table(),
        new TableHeader(),
        new TableCell(),
        new TableRow(),
        new FormatClear(),
        new TextColor(),
        new TextHighlight(),
        new Preview(),
        new Print(),
        new Fullscreen(),
        new SelectAll(),
        new FontType(),
        new FontSize(),
        // new CodeView(),
      ],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.loadChannels();

    //如果有id那么 就获取
    if (this.$route.query.id) {
      this.loadArticle();
    }
  },
  mounted() {},
  methods: {
    loadChannels() {
      getArticleChannels().then((res) => {
        this.channels = res.data.data.channels;
      });
    },
    onSubmit(draft = false) {
      this.$refs["publish-form"].validate((valid) => {
        if (!valid) {
          return;
        } else {
          //公用一个组件 来判断一下是修改还是发布操作
          //如果他是有 文章id的那么就是在修改 没有则是上传
          const articleId = this.$route.query.id;
          if (articleId) {
            updateArticle(articleId, this.article, draft).then((res) => {
              // console.log(res);
              this.$message({
                message: `${draft ? "存入草稿" : "发布成功"}`,
                type: "success",
              });
            });
          } else {
            //提交 数据接口已没有了
            // console.log(this.article);
            addArticle(this.article, draft).then((res) => {
              // console.log(res);
              this.$message({
                message: `${draft ? "存入草稿" : "发布成功"}`,
                type: "success",
              });
              //完成之后跳转
              this.$router.push("/article");
            });
          }
        }
      });
    },
    //根据id加载文章
    loadArticle() {
      getArticle(this.$route.query.id).then((res) => {
        console.log(res.data);
        //以id获取数据的接口也不能用了
        // this.article = res.data.data //无效值
      });
    },
    onUpadateCover(index,url){
      // console.log(index,url);
      this.article.cover.images[index] = url
    }
  },
};
</script>

<style scoped lang="less">
.uploadcover{
  display: flex;
  flex-direction: row;
}
</style>